﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DCS.ComLib.Config;
using VietThuongLMS.Services;
using VietThuongLMS.ViewModels;
using VietThuongLMS.Utils;
using System.Web.Security;
using VietThuongLMS.Areas.Admin.Models;

namespace VietThuongLMS.Areas.Admin.Controllers
{

    public class LopHocController : Controller
    {
        //
        // GET: /Admin/LopHoc/
        //[Authorize(Roles = "Admin")]

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Index()
        {
            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            TaiKhoan account = AccountService.GetTaiKhoanVaLoai(HttpContext.User.Identity.Name);
            LopHocViewModel LopHocList;
            if(account.MaLoaiTaiKhoan == "Admin")
                LopHocList = LopHocService.GetLopHocList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page);
            else
                LopHocList = LopHocService.GetLopHocList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page, HttpContext.User.Identity.Name);

            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "LopHoc", "Index", "?p=", LopHocList.Total, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            //end phân trang

            return View(LopHocList);
        }

        //
        // GET: /Admin/LopHoc/Details/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Detail(int id)
        {
            LMSDataEntities context = new LMSDataEntities();
            LopHocDetailViewModel viewModel = new LopHocDetailViewModel();

            viewModel.LopHocViewModel = context.PhanCongs.Join(context.GiaoViens,
                pc => pc.MaGiaoVien,
                gv => gv.ID,
                //(pc, gv) => pc).Join(context.CaHocs,
                //pc => pc.MaCaHoc,
                //ch => ch.ID,
                (pc, ch) => pc).Join(context.LopHocs,
                pc => pc.MaLopHoc,
                l => l.ID,
                (pc, l) => l).Join(context.MonHocs,
                l => l.MaMonHoc,
                m => m.ID,
                (l, m) => l).Join(context.LoaiLopHocs,
                l => l.MaLoaiLopHoc,
                llh => llh.ID,
                (l, llh) => l).Join(context.ChiNhanhs,
                l => l.MaChiNhanh,
                cn => cn.ID,
                (l, cn) => l).Where(l => l.ID == id).FirstOrDefault();

            //viewModel.LopHocViewModel = LopHocService.GetLopHocById(id);
            PhanCong phanCong = context.PhanCongs.FirstOrDefault(p => p.MaLopHoc == id);
            if (phanCong != null)
            {
                viewModel.PhanCongViewModel = context.PhanCongs.Join(context.LopHocs,
                    pc => pc.MaLopHoc,
                    l => l.ID,
                    (pc, l) => pc).Join(context.GiaoViens,
                    pc => pc.MaGiaoVien,
                    gv => gv.ID,
                    //(pc, gv) => pc).Join(context.CaHocs,
                    //pc => pc.MaCaHoc,
                    //ch => ch.ID,
                    (pc, ch) => pc).Where(p => p.ID == phanCong.ID).FirstOrDefault();
            }
            //viewModel.LopHoc_HocVienLopViewModel = context.HocVien_Lop.Join(context.LopHocs,
            //    pc => pc.MaLopHoc,
            //    l => l.ID,
            //    (pc, l) => pc).Join(context.GiaoViens,
            //    pc => pc.MaGiaoVien,
            //    gv => gv.ID,
            //    (pc, gv) => pc).Join(context.CaHocs,
            //    pc => pc.MaCaHoc,
            //    ch => ch.ID,
            //    (pc, ch) => pc).FirstOrDefault();

            //NHDuc added
            HocVien_LopViewModel hocVienList = HocVien_LopService.GetHocVienLopByLopIdList(id);
            foreach (HocVien_LopMoRongModel model in hocVienList.ListMoRong)
            {
                if (model.HV_L.ChuyenDe != null)
                { model.HV_L.ChuyenDe = (new Converter()).ChuyenDeParser(model.HV_L.ChuyenDe); }
            }
            viewModel.HocVienList = hocVienList;
            //end NHDuc

            return View(viewModel);
        }

        //
        // GET: /Admin/LopHoc/Create
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Create()
        {
            using (LMSDataEntities context = new LMSDataEntities())
            {
                LopHoc lh = new LopHoc();
                List<object> values = new List<object>();
                values.Add(new { ID = "Thứ 2", Name = "Thứ 2" });
                values.Add(new { ID = "Thứ 3", Name = "Thứ 3" });
                values.Add(new { ID = "Thứ 4", Name = "Thứ 4" });
                values.Add(new { ID = "Thứ 5", Name = "Thứ 5" });
                values.Add(new { ID = "Thứ 6", Name = "Thứ 6" });
                values.Add(new { ID = "Thứ 7", Name = "Thứ 7" });
                values.Add(new { ID = "Chủ Nhật", Name = "Chủ Nhật" });

                IEnumerable<SelectListItem> loaiLH = new SelectList(context.LoaiLopHocs.ToList(), "ID", "MoTa");
                ViewData["LoaiLH"] = loaiLH;

                IEnumerable<SelectListItem> maMH = new SelectList(context.MonHocs.ToList(), "ID", "TenMonHoc");
                ViewData["MaMH"] = maMH;

                IEnumerable<SelectListItem> maGV = new SelectList(context.GiaoViens.Join(context.TaiKhoans, a => a.MaTaiKhoan, t => t.ID,
                    (a, t) => new
                    {
                        GiaoVienID = a.ID,
                        GiaoVienName = t.HoTen
                    }
                ).ToList(), "GiaoVienID", "GiaoVienName");

                ViewData["MaGV"] = maGV;

                ViewData["Thu"] = new SelectList(values, "ID", "Name");

                //IEnumerable<SelectListItem> caHoc = new SelectList(context.CaHocs.Select( s => new
                //    {
                //        ID = s.ID,
                //        TenCaHoc = s.ThoiGianBatDau + " - " + s.ThoiGianKetThuc,
                //    }
                //).ToList(), "ID", "TenCaHoc");

                //IEnumerable<SelectListItem> caHoc = new SelectList(context.CaHocs.ToList(), "ID", "ThoiGianBatDau"+"-"+"ThoiGianKetThuc");
                //ViewData["CaHoc"] = caHoc;

                IEnumerable<SelectListItem> maCN = new SelectList(context.ChiNhanhs.ToList(), "ID", "TenChiNhanh");
                ViewData["MaCN"] = maCN;

                return View();
            }
        } 

        //
        // POST: /Admin/LopHoc/Create
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(LopHocModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    
                    // TODO: Add insert logic here
                    LopHoc data = new LopHoc();
                    Converter cv = new Converter();
                    DateTime ngayKhaiGiang = cv.StringToDate(model.NgayKhaiGiang);

                    data.NgayKhaiGiang = ngayKhaiGiang;
                    data.NgayKetThuc = null;
                    //data.NgayKetThuc = model.NgayKetThuc;
                    data.TinhTrang = Constant.SAP_MO;
                    data.TenLopHoc = model.TenLopHoc;
                    data.NgonNgu = model.NgonNgu;
                    data.MaLoaiLopHoc = int.Parse(model.LoaiLH);
                    data.MaMonHoc = int.Parse(model.MaMH);
                    data.MaChiNhanh = int.Parse(model.MaCN);
                    data.Deleted = Constant.GENERAL_STATUS_NORMAL;
                    data.SoLuong = model.SoLuong;

                    int maLopHoc = LopHocService.InsertLopHocReturn(data);
                    if (maLopHoc != Constant.RETURNCODE_ERROR)
                    {
                        //Sau khúc này, thì nó insert vào db đúng iu cầu trong bảng lớp học rồi
                        //Insert vao bang phan cong 12 dong tuong ung vs 12 buoi
                        bool r = PhanCongService.InsertPhanCongTKB(maLopHoc, int.Parse(model.MaGV), model.CaHoc,
                                            model.Thu.ToString(), model.NgayKhaiGiang.ToString());
                        if(r)
                            return RedirectToAction("Index", "LopHoc", new { area = "Admin" });
                    }
                    using (LMSDataEntities context = new LMSDataEntities())
                    {
                        List<object> values = new List<object>();
                        values.Add(new { ID = "Thứ 2", Name = "Thứ 2" });
                        values.Add(new { ID = "Thứ 3", Name = "Thứ 3" });
                        values.Add(new { ID = "Thứ 4", Name = "Thứ 4" });
                        values.Add(new { ID = "Thứ 5", Name = "Thứ 5" });
                        values.Add(new { ID = "Thứ 6", Name = "Thứ 6" });
                        values.Add(new { ID = "Thứ 7", Name = "Thứ 7" });
                        values.Add(new { ID = "Chủ Nhật", Name = "Chủ Nhật" });

                        IEnumerable<SelectListItem> loaiLH = new SelectList(context.LoaiLopHocs.ToList(), "ID", "MoTa");
                        ViewData["LoaiLH"] = loaiLH;

                        IEnumerable<SelectListItem> maMH = new SelectList(context.MonHocs.ToList(), "ID", "TenMonHoc");
                        ViewData["MaMH"] = maMH;

                        IEnumerable<SelectListItem> maGV = new SelectList(context.GiaoViens.Join(context.TaiKhoans, a => a.MaTaiKhoan, t => t.ID,
                            (a, t) => new
                            {
                                GiaoVienID = a.ID,
                                GiaoVienName = t.HoTen
                            }
                        ).ToList(), "GiaoVienID", "GiaoVienName");

                        ViewData["MaGV"] = maGV;

                        ViewData["Thu"] = new SelectList(values, "ID", "Name");

                        //IEnumerable<SelectListItem> caHoc = new SelectList(context.CaHocs.ToList(), "ID", "TenCaHoc");

                        //IEnumerable<SelectListItem> caHoc = new SelectList(context.CaHocs.Select(s => new
                        //{
                        //    ID = s.ID,
                        //    TenCaHoc = s.ThoiGianBatDau + " - " + s.ThoiGianKetThuc,
                        //}
                        //).ToList(), "ID", "TenCaHoc");

                        //ViewData["CaHoc"] = caHoc;

                        IEnumerable<SelectListItem> maCN = new SelectList(context.ChiNhanhs.ToList(), "ID", "TenChiNhanh");
                        ViewData["MaCN"] = maCN;

                        return View(model);
                    }
                }
                catch (Exception ex)
                {
                    DCS.ComLib.File.Log.Write("LopHocController::Create", ex.StackTrace, ex.Message);
                    return View("Create", model);
                }
            }
            //Invalid, redisplay form with errors
            return View("Create", model);
        }
        
        //
        // GET: /Admin/LopHoc/Edit/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Edit(int id)
        {
            //LopHoc lh = LopHocService.GetLopHocById(id);

            LMSDataEntities context = new LMSDataEntities();
            LopHoc lh = new LopHoc();

            lh = context.LopHocs.Join(context.LoaiLopHocs,
                l => l.MaLoaiLopHoc,
                llh => llh.ID,
                (l, llh) => l).Join(context.MonHocs,
                l => l.MaMonHoc,
                mh => mh.ID,
                (l, mh) => l).Where(l => l.ID == id).FirstOrDefault();

            IEnumerable<SelectListItem> maCN = new SelectList(context.ChiNhanhs.ToList(), "ID", "TenChiNhanh", lh.MaChiNhanh);
            ViewData["MaCN"] = maCN;

            //PhanCong pc = new PhanCong();

            //lh = context.PhanCongs.Join(context.GiaoViens,
            //pc => pc.MaGiaoVien,
            //gv => gv.ID,
            //(pc, gv) => pc).Join(context.CaHocs,
            //pc => pc.MaCaHoc,
            //ch => ch.ID,
            //(pc, ch) => pc).Join(context.LopHocs,
            //pc => pc.MaLopHoc,
            //l => l.ID,
            //(pc, l) => l).Join(context.MonHocs,
            //l => l.MaMonHoc,
            //m => m.ID,
            //(l, m) => l).Join(context.LoaiLopHocs,
            //l => l.MaLoaiLopHoc,
            //llh => llh.ID,
            //(l, llh) => l).Where(l => l.ID == id).FirstOrDefault();

            //lh = context.PhanCongs.Join(context.LopHocs,
            //    p => p.MaLopHoc,
            //    lh2 => lh2.ID,
            //    (p, lh2) => p).Where(p => p.MaLopHoc == id).FirstOrDefault();

            //int maLopHoc = int.Parse(lh.MaLoaiLopHoc.ToString());
            //int maMonHoc = int.Parse(lh.MaMonHoc.ToString());

            //using (LMSDataEntities context = new LMSDataEntities())
            //{
                //List<object> values = new List<object>();
                //values.Add(new { ID = "Thứ 2", Name = "Thứ 2" });
                //values.Add(new { ID = "Thứ 3", Name = "Thứ 3" });
                //values.Add(new { ID = "Thứ 4", Name = "Thứ 4" });
                //values.Add(new { ID = "Thứ 5", Name = "Thứ 5" });
                //values.Add(new { ID = "Thứ 6", Name = "Thứ 6" });
                //values.Add(new { ID = "Thứ 7", Name = "Thứ 7" });
                //values.Add(new { ID = "Chủ Nhật", Name = "Chủ Nhật" });

                //ViewData["LoaiLH"] = new SelectList(context.LoaiLopHocs.ToList(), "ID", "MoTa", lh.MaLoaiLopHoc);
                //ViewData["MaMH"] = new SelectList(context.MonHocs.ToList(), "ID", "TenMonHoc", lh.MaMonHoc);
                //ViewData["MaGV"] = new SelectList(context.GiaoViens.Join(context.TaiKhoans, a => a.MaTaiKhoan, t => t.ID,
                //    (a, t) => new
                //    {
                //        GiaoVienID = a.ID,
                //        GiaoVienName = t.HoTen
                //    }
                //).ToList(), "GiaoVienID", "GiaoVienName");

                //ViewData["Thu"] = new SelectList(values, "ID", "Name");
                //ViewData["CaHoc"] = new SelectList(context.CaHocs.ToList(), "ID", "TenCaHoc");
            //}
            return View(lh);
        }


        // POST: /Admin/LopHoc/Edit/5
        // [Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(LopHocModel model, int id)
        {
            try
            {
                // TODO: Add update logic here
                LopHoc lh = LopHocService.GetLopHocById(id);

                lh.MaChiNhanh = int.Parse(model.MaCN);
                lh.TenLopHoc = model.TenLopHoc;
                lh.NgonNgu = model.NgonNgu;
                lh.TinhTrang = model.TinhTrang;
                lh.SoLuong = model.SoLuong;

                LopHocService.Edit(lh);

                //return View(lh);
                //IEnumerable<SelectListItem> maCN = new SelectList(context.ChiNhanhs.ToList(), "ID", "TenChiNhanh", nv.MaChiNhanh);
                //ViewData["MaCN"] = maCN;

                return RedirectToAction("Index", "LopHoc", new { area = "Admin" });
            }
            catch (Exception ex)
            {
                DCS.ComLib.File.Log.Write("LopHocController::Edit", ex.StackTrace, ex.Message);
                return View();
            }
        }

        // POST: /Admin/LopHoc/Delete/5
        //[Authorize(Roles = "Admin")]
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpGet]
        public ActionResult Delete(int id)
        {
            // TODO: Add delete logic here

            bool result = LopHocService.DeleteLopHoc(id);
            if (result)
            {
                return RedirectToAction("Index", "LopHoc", new { area = "Admin" });
            }
            else
            {
                return View();
            }
        }

        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost]
        public bool CheckValid(string tenLopHoc)
        {
            if(LopHocService.GetLopHoc(tenLopHoc) != null)
                return false;
            return true;
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Search()
        {
            LMSDataEntities context = new LMSDataEntities();
            
            List<object> values = new List<object>();
            values.Add(new { ID = "", Name = "Tất Cả" });
            values.Add(new { ID = "Sắp Mở", Name = "Sắp Mở" });
            values.Add(new { ID = "Đang Học", Name = "Đang Học" });
            values.Add(new { ID = "Kết Thúc", Name = "Kết Thúc" });

            IEnumerable<SelectListItem> loaiLH = new SelectList(context.LoaiLopHocs.ToList(), "ID", "MoTa");
            ViewData["loailophoc"] = loaiLH;

            ViewData["tinhtrang"] = new SelectList(values, "ID", "Name");
            return View();
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult SearchResult(string s, string type)
        {
            LMSDataEntities context = new LMSDataEntities();
            var lh = new List<LopHoc>();

            if (s != "")
            {
                switch (type)
                {
                    case "ten":
                        lh = context.LopHocs.Where(a => a.TenLopHoc.Contains(s)).ToList();
                        break;
                    case "tinhtrang":
                        lh = context.LopHocs.Where(a => a.TinhTrang.Contains(s)).ToList();
                        break;
                    case "loailophoc":
                        lh = context.LopHocs.Where(a => a.LoaiLopHoc.MoTa.Contains(s)).ToList();
                        break;
                    default:
                        lh = context.LopHocs.ToList();
                        //lh = context.LopHocs.Where(a => a.TenLopHoc.Contains(s) || a.TinhTrang.Contains(s) || a.NgonNgu.Contains(s)
                        //    || a.LoaiLopHoc.MoTa.Contains(s)).ToList();
                        break;
                }
            }
            else
            {
                lh = context.LopHocs.ToList();
            }

            LopHocViewModel lhm = new LopHocViewModel(lh, lh.Count());
            return PartialView(lhm);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult LopHocThuPhi()
        {
            return View();
        }
    }
}
